import time
from frame_work.browser_engine import BrowserEngine
from page_object.rebate_page import RebatePage
from frame_work.logger import Logger
from frame_work.login import PcLogin
from frame_work.util import check_tid, get_sql_info, get_jid
from frame_work import menu_list
from frame_work.setting import *
from frame_work.yaml_file import YAML
from frame_work.read_config import global_config
# 导入NoSuchElementException
from selenium.common.exceptions import NoSuchElementException

logger = Logger(__name__).get_logger()


class ModshowRebate(object):

    def __init__(self, tid):
        self.tid = tid
        self.driver = None
        self.session = self.get_session()
        self.yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))
        self.domain = self.yaml.get_data('domain')

    def get_session(self):
        """
        返回session
        :return:
        """
        statement = """SELECT uname from sk_try where tid = %s"""
        params = (self.tid,)
        value = get_sql_info(statement, params, meta={
            "info": "查询活动商家名称uname"
        })

        login = PcLogin(value[0].get("uname"))
        login.pc_login()
        session = login.get_session()
        return session

    def get_cookies_info(self):
        """
        通过传递过来的session获取cookies
        :return:
        """

        cookies_dict = {'domain': '.' + self.domain + '.com',
                        'name': '',
                        'value': '',
                        'path': '/',
                        'httpOnly': True,
                        'secure': False}
        for c_name, c_value in self.session.cookies.items():
            if c_name == 'shikee':
                cookies_dict.update({"name": c_name, "value": c_value})
        return cookies_dict

    def modshow_rebate(self, uname):
        """
        后台执行返款
        :return:
        """
        jid = get_jid(self.tid, uname)
        if jid:
            browser = BrowserEngine()
            self.driver = browser.open_browser()
            cookies_dict = self.get_cookies_info()
            self.rebate_Page = RebatePage(self.driver)
            rebate_url = self.yaml.get_data(
                'modshow_rebate_pwd')['url'] + '?jid=' + str(jid[0].get('jid'))
            self.driver.get(rebate_url)  # 需要先请求一次
            # 对cookie进行操作
            self.rebate_Page.cookie("add", **cookies_dict)
            self.driver.get(rebate_url)  # 第二次请求
            logger.info("开始奖励给试客活动款")
            self.rebate_Page.click_rebate_btn()
            # self.pay_Page.wait_pay_title(5)#显示等待支付页面元素加载完
            time.sleep(3)
            self.rebate_Page.switch_password_frame(0)
            # 不确定用户支付密码哪个正确,config.ini配置多个密码,循环读取并判断
            pay_pwd = global_config.get_pwd('payPwd')
            pay_pwd = pay_pwd.split(',')
            for pwd in pay_pwd:
                self.rebate_Page.input_password(pwd)
                self.rebate_Page.click_confirm()
                time.sleep(2)
                try:
                    text = self.rebate_Page.get_error_tips()
                    if not text:
                        raise NoSuchElementException
                    logger.info("错误信息:%s" % text)
                except NoSuchElementException:
                    logger.info("支付密码%s正确" % pwd)
                    break
            time.sleep(2)
            logger.debug("回跳到联盟奖励成功页面，地址: %s" % self.driver.current_url)
            current_url = self.driver.current_url
            # value = self.yaml.get_data('rebate_pwd')[
            #     'result'] + "?jid=" + str(jid[0].get('jid'))  # 比对值
            logger.debug("奖励活动款结束")
            self.check_result(current_url, rebate_url)

    def check_result(self, value1, value2):
        """
        比对结果
        :param value1:
        :param value2:
        :return:
        """
        logger.debug("开始比对")
        try:
            if value1 != value2:
                raise Exception("比对结果不一致！")
        except Exception as e:
            logger.info("有密返款失败,可能互联环境不稳定导致 Reason : %s" % (e))
        else:
            logger.info("试客奖励活动款成功")
        finally:
            self.driver.quit()


def main():
    while True:
        # 显示功能菜单
        menu_list.modshow_rebate()
        # 选择
        choise = input("请输入您的选择: ")
        if choise in ('q', 'Q'):
            break
        try:
            tid = int(input(u'请输入活动tid: '))
            status = check_tid(tid)
            if not status:
                raise Exception("活动tid不存在try表，请核实后在重新输入")
        except Exception as e:
            logger.error("reszon => %s" % e)
        else:
            buyer_name = input(u'请输入要奖励的试客名称: ')
            rebate = ModshowRebate(tid)
            rebate.modshow_rebate(buyer_name)


if __name__ == '__main__':
    # suite = unittest.TestLoader().loadTestsFromTestCase(PayQuantity)
    # runner=unittest.TextTestRunner()
    # runner.run(suite)
    main()
